package com.saas.tenant.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.saas.tenant.dto.LoginDTO;
import com.saas.tenant.dto.TenantDTO;
import com.saas.tenant.entity.Tenant;
import com.saas.tenant.entity.User;
import com.saas.tenant.mapper.TenantMapper;
import com.saas.tenant.mapper.UserMapper;
import com.saas.tenant.resp.LoginResp;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import lombok.RequiredArgsConstructor;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class TenantService {

    private final TenantMapper tenantMapper;
    private final UserMapper userMapper;
    private final BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();

    /** 注册租户 + 超管用户 */
    @Transactional
    public Map<String, Object> createTenantWithAdmin(TenantDTO dto) {
        // 1. 建租户
        Tenant t = new Tenant();
        t.setTenantCode(dto.getTenantCode());
        t.setTenantName(dto.getTenantName());
        t.setPackageId(0);
        t.setStatus(1);
        tenantMapper.insert(t);

        // 2. 建超管用户
        User u = new User();
        u.setTenantId(t.getId());
        u.setOrgId(1L);               // 根部门，后面再补 org 表
        u.setUsername(dto.getUsername());
        u.setEmail(dto.getEmail());
        u.setPhone(dto.getPhone());
        u.setPasswordHash(encoder.encode(dto.getPassword()));
        u.setStatus(1);
        userMapper.insert(u);

        return Map.of("tenantId", t.getId(), "userId", u.getId());
    }

    /** 登录 → 返回 JWT */
    public LoginResp login(LoginDTO dto) {
        User u = userMapper.selectOne(
                new QueryWrapper<User>().eq("username", dto.getUsername())
                        .eq("tenant_id", dto.getTenantId()));
        if (u == null || !encoder.matches(dto.getPassword(), u.getPasswordHash())) {
            throw new RuntimeException("用户名或密码错误");
        }

        // 1. 生成安全密钥
        SecretKey key = Keys.hmacShaKeyFor("12345678901234567890123456789012"
                .getBytes(StandardCharsets.UTF_8));

        // 2. 构建 token
        String token = Jwts.builder()
                .setSubject(u.getId().toString())
                .claim("tenantId", u.getTenantId())
                .setExpiration(new Date(System.currentTimeMillis() + 15 * 60 * 1000))
                .signWith(key)
                .compact();

        return new LoginResp(token, u.getUsername());
    }
}